package n1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * @author wxc
 * @date 2021年09月14日 17:13
 */
public class Server {

    public static void main(String[] args)  {
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            serverSocket = new ServerSocket(9998);

            socket = serverSocket.accept();
            // 取出输入流中的byte[]
            byte[] bytes = StreamUtils.streamToByteArray(
                    new BufferedInputStream(socket.getInputStream()));
            // 写到文件中
            String fileName = "./lovely.png";
            bufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(fileName));
            bufferedOutputStream.write(bytes);
            // 返回给客户端成功的响应
            BufferedWriter bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("收到啦");
            bufferedWriter.flush();
            socket.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
